var hosturl = "https://bab.moreqifu.cn";
var spareurl = "https://fss.mpay8.cn";
var links = {};
var requestData = {};
var urlscheme = "";
var nowtimestamp = "";
var isrequest = true;
var record_id = "";
var urlParamsStatus = false;
var urlParams = {};
var back_platfrom = "";

$(document).ready(function() {
    var copylink = new ClipboardJS("#copylink");
    copylink.on('success', function(e) {
        showDialog();
    });
    var copylink = new ClipboardJS("#errorcopylink");
    copylink.on('success', function(e) {
        showDialog();
    });
});

function getLinksDetial() {
    nowtimestamp = Math.round(new Date().getTime()/1000).toString();
    browser = getBrowser();
    $("#main_content").show();
    try {
        links = JSON.parse(aesDncryptDefault(linksInfo));
        console.log(links);
        renderCopyLink();
        if (links.hasOwnProperty("links_id")) {
            requestDataMethod();
        }
        if (links.links_id == "") {
            noticeError("链接异常提醒","访问接口异常,请检查链接是否错误!","error");
            return;
        }
    } catch(err){
        noticeError("链接异常提醒","访问接口异常,请检查链接是否错误!","error");
        return;
    }
    if (links.disable != 1) {
        noticeError("链接异常提醒","访问接口异常,请检查链接是否错误!","error");
        return;
    }


    if(links.platfrom_type == 7) {
        // 复制搜索模式
        window.location.href = spareurl+"/copy/"+links.links_id;
        return;
    } else if(links.platfrom_type == 10) {
        // 朋友圈分享陌生
        window.location.href = spareurl+"/share/"+links.links_id;
        return;
    }

    // 微信环境直接跳转
    var weixin = isWeiXin();
    if (weixin) {
        renderWeixin();
        return;
    }

    var query = getQueryString("query");
    if (query != "") links.query = query;
    var path = getQueryString("path");
    if (path != "") links.path = path;
    var third_appid = getQueryString("third_appid");
    if (third_appid != "") links.third_appid = third_appid;

    renderStyles();

    // 审核模式完全不跳转
    if (links.styles.redirect_style == 3) {
        console.log("examine");
        return;
    }
    getUrlParamLists();
    requestParams().then(function (v) {
        if (urlParams.hasOwnProperty("debug_sign")) {
            if (urlParams.debug_time <= current_time) {
                siteErrorNotice(1001,"落地页过期提醒","联调落地页链接有效期为1小时,请前往后台重新获取!");
                return;
            }
            var debug_sign = CryptoJS.MD5(links.links_id+urlParams.debug_time).toString();
            if (debug_sign != urlParams.debug_sign) {
                siteErrorNotice(1001,"链接错误提醒","联调落地页链接错误,请确认获取的链接是否正确!");
                return;
            }
            // 清空缓存方便联调
            removeCache();
        }
        var weibo = isWeibo();
        var cacheurlschme = localStorage.getItem("cacheurlschme"+links.links_id) || '{"urlscheme":"","timestamp":""}';
        var schemeCacheData = JSON.parse(cacheurlschme);
        if (schemeCacheData.urlscheme == ""){
            // 如果存在缓存不调用接口
            if (weibo) {
                renderWeibo();
            } else {
                // 调用API接口
                requestApi(1);
            }
        } else {
            // 超过缓存时间重新访问,缓存3分钟
            if ((parseInt(nowtimestamp) - parseInt(schemeCacheData.timestamp)) > 180) {
                if (weibo) {
                    renderWeibo();
                } else {
                    // 调用API接口
                    requestApi(1);
                }
            } else {
                urlscheme = schemeCacheData.urlscheme;
                if (links.styles.style == 1 || links.styles.style == 2) {
                    if (links.styles.gif_show != 3) {
                        $("#dianjiimg_links").attr('href',urlscheme);
                    }
                    $("#public-web-jump-button").attr("href",urlscheme);
                } else if(links.styles.style == 4){
                } else if(links.styles.style == 5){
                    $(".miniapp-btn").attr("href",urlscheme);
                }else {
                    $("#dianjiimg_links_full").attr('href',urlscheme);
                    $("#public-web-jump-button-full").attr("href",urlscheme)
                }
                platformCompatibility();
            }
        }
    });
    copyrightShow();
}

function removeCache() {
    localStorage.removeItem("cacheurlschme"+links.links_id);
    localStorage.removeItem("ttwlstatic_"+links.links_id);
    localStorage.removeItem("record_id_"+links.links_id);
}


function renderCopyLink() {
    try {
        if (links.platfrom_type == 1) {
            $(".weui-msg__desc").text("如链接无法打开微信公众号，请复制到微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信公众号，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 2 || links.platfrom_type == 3) {
            $(".weui-msg__desc").text("如链接无法打开微信并打开客服界面，请复制到微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信并打开客服界面，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 4) {
            $(".weui-msg__desc").text("如链接无法打开微信小程序，请复制到微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信小程序，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 6) {
            $(".weui-msg__desc").text("如链接无法打开微信小程序，请复制到微信打开。 ");
            $(".copy-notice font").text("如果链接无法打开微信小程序，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 8 || links.platfrom_type == 9) {
            $(".weui-msg__desc").text("如链接无法打开微信二维码，请复制到微信打开。");
            $(".copy-notice font").text("如链接无法打开微信展示二维码，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 11) {
            $(".weui-msg__desc").text("如链接无法打开微信小程序码，请复制到微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信小程序码，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 12) {
            $(".weui-msg__desc").text("如链接无法打开微信公众号二维码，请复制到微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信公众号二维码，请复制到微信打开；点击 ");
            $(".copy-notice").show();
        }
        $("#copylink").attr("data-clipboard-text",window.location.href);
        $("#errorcopylink").attr("data-clipboard-text",window.location.href);
    } catch(err){
        errorReport("renderCopyLink---\r\n"+err);
    }
}

function generateRecordId() {
    var storageRecordId = localStorage.getItem("record_id_"+links.links_id) || "";
    if (storageRecordId == "") {
        var tableId = (new Date().getMonth()+1) % 4;
        var vertify = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var sd = '';
        var links_id = links.links_id;
        for (var i = 0; i < 10; i++) {
            var random = Math.floor(Math.random() * (vertify.length));
            sd += vertify[random];
        }
        var recordId = CryptoJS.MD5(links.links_id+nowtimestamp+sd).toString();
        record_id = tableId+recordId;
        localStorage.setItem("record_id_"+links.links_id,record_id);
    } else {
        record_id = storageRecordId;
    }
    return record_id;
}

function requestParams() {
    return new Promise((resolve1, reject1)=>{
        // 点击ID,每个广告唯一
        var p1 = new Promise((resolve, reject) => {
            var clickid = "";
            var adid = "";
            if (!urlParamsStatus) {
                setTimeout(function(){
                    back_platfrom = urlParams.back_platfrom || "";
                    if (urlParams.back_platfrom == "dy" || browser == "douyin") {
                        clickid = urlParams.hasOwnProperty('clickid') ? urlParams.clickid : "";
                        adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "dy";
                        }
                    } else if (urlParams.back_platfrom == "bd" || browser == "baidu") {
                        clickid = urlParams.hasOwnProperty('bd_vid') ? urlParams.bd_vid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "bd";
                        }
                    } else if (urlParams.back_platfrom == "ks" || browser == "kuaishou") {
                        clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                        adid = urlParams.hasOwnProperty('aid') ? urlParams.aid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "ks";
                        }
                    } else if (urlParams.back_platfrom == "bili") {
                        clickid = urlParams.trackid;
                        adid = urlParams.campaignid;
                    } else if (urlParams.back_platfrom == "zh") {
                        cburl = urlParams.cb;
                        url = decodeURIComponent(cburl);
                        clickid = getOtherUrlParam(url,"sessionId");
                    } else if (urlParams.back_platfrom == "xmly") {
                        clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                        adid = urlParams.hasOwnProperty('materialid') ? urlParams.materialid : "";
                    } else if (urlParams.back_platfrom == "gdt") {
                        clickid = urlParams.hasOwnProperty('gdt_vid') ? urlParams.gdt_vid : urlParams.qz_gdt;
                        adid = urlParams.hasOwnProperty('wx_aid') ? urlParams.wx_aid : "";
                    } else if (urlParams.back_platfrom == "oppo") {
                        clickid = urlParams.hasOwnProperty('tid') ? urlParams.tid : "";
                        adid = urlParams.hasOwnProperty('pageId') ? urlParams.pageId : "";
                    } else if (urlParams.back_platfrom == "vivo") {
                        clickid = urlParams.hasOwnProperty('requestid') ? urlParams.requestid : "";
                        adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                    }
                    resolve({"clickid":clickid,"adid":adid})
                }, 100);
            } else {
                back_platfrom = urlParams.back_platfrom || "";
                if (urlParams.back_platfrom == "dy" || browser == "douyin") {
                    clickid = urlParams.hasOwnProperty('clickid') ? urlParams.clickid : "";
                    adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                    if (typeof(back_platfrom) == "undefined" && clickid != "") {
                        back_platfrom = "dy";
                    }
                } else if (urlParams.back_platfrom == "bd" || browser == "baidu") {
                    clickid = urlParams.hasOwnProperty('bd_vid') ? urlParams.bd_vid : "";
                    if (typeof(back_platfrom) == "undefined" && clickid != "") {
                        back_platfrom = "bd";
                    }
                } else if (urlParams.back_platfrom == "ks" || browser == "kuaishou") {
                        clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                        adid = urlParams.hasOwnProperty('aid') ? urlParams.aid : "";
                        if (typeof(back_platfrom) == "undefined" && clickid != "") {
                            back_platfrom = "ks";
                        }
                } else if (urlParams.back_platfrom == "bili") {
                    clickid = urlParams.trackid;
                    adid = urlParams.campaignid;
                } else if (urlParams.back_platfrom == "zh") {
                    cburl = urlParams.cb;
                    url = decodeURIComponent(cburl);
                    clickid = getOtherUrlParam(url,"sessionId");
                } else if (urlParams.back_platfrom == "xmly") {
                    clickid = urlParams.hasOwnProperty('callback') ? urlParams.callback : "";
                    adid = urlParams.hasOwnProperty('materialid') ? urlParams.materialid : "";
                } else if (urlParams.back_platfrom == "gdt") {
                    clickid = urlParams.hasOwnProperty('gdt_vid') ? urlParams.gdt_vid : urlParams.qz_gdt;
                    adid = urlParams.hasOwnProperty('wx_aid') ? urlParams.wx_aid : "";
                } else if (urlParams.back_platfrom == "oppo") {
                    clickid = urlParams.hasOwnProperty('tid') ? urlParams.tid : "";
                    adid = urlParams.hasOwnProperty('pageId') ? urlParams.pageId : "";
                } else if (urlParams.back_platfrom == "vivo") {
                    clickid = urlParams.hasOwnProperty('requestid') ? urlParams.requestid : "";
                    adid = urlParams.hasOwnProperty('adid') ? urlParams.adid : "";
                }
                resolve({"clickid":clickid,"adid":adid})
            }
        })
     
        Promise.all([p1]).then((result) => {
            var resultData = result[0];
            requestData["clickid"] = resultData.clickid;
            requestData["adid"] = resultData.adid;
            requestData["back_platfrom"] = back_platfrom;
            resolve1({});
        })
    });
}

function getUrlParamLists() {
    var search = window.location.search;
    query = search.replace("?","");
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        urlParams[pair[0]] = pair[1];
        if (i == (vars.length-1)) {
            urlParamsStatus = true;
        }
    }
}

function requestDataMethod() {
    var leftlength = 16 - links.links_id.length;
    if (leftlength >= 0) {
        var key = links.links_id;
        for (var i = 0; i < leftlength; i++) {
            key += "W";
        }
    } else {
        var key = links.links_id.slice(0,16);
    }
    var timestamp = parseInt(nowtimestamp) + 180;
    var iv = timestamp+"WLWLWL";
    var saltstart = "wl";
    var saltend = "lw";
    requestData["sign"] = CryptoJS.MD5(saltstart+iv+key+iv+saltend).toString();
    requestData["token"] = CryptoJS.MD5(links.appid+iv+key+iv+saltend).toString();
    requestData["record_id"] = generateRecordId();
    requestData["key"] = key;
    requestData["timestamp"] = timestamp;
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return "";
}

function getBrowser() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.search('jssdk') != -1 || userAgent.search('aweme') != -1 || userAgent.search('bytelocale') != -1 || userAgent.search('bytedancewebview') != -1) {
        return "douyin";
    } else if (userAgent.search('baiduboxapp') != -1) {
        return "baidu";
    } else if (userAgent.search('kwai') != -1) {
        return "kuaishou";
    } else {
        return "other";
    }
}

function aesEncrypt(str, key, iv) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.enc.Utf8.parse(iv);
    var encrypted = CryptoJS.AES.encrypt(str,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}

function aesDecrypt(str, key, iv) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.enc.Utf8.parse(iv);
    var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
    return decrypted.toString(CryptoJS.enc.Utf8);
}

function aesDncryptDefault(str) {
    var key = CryptoJS.enc.Utf8.parse("Mn2sd56Msd789888");
    var iv = CryptoJS.enc.Utf8.parse("S221456Msd789888");
    var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
    return decrypted.toString(CryptoJS.enc.Utf8);
}

function noticeError(title,message,status) {
    $(".site-contain").hide();
    $(".weui-msg__title").text(title);
    $(".weui-msg__desc").text(message);
    if (status == "error") {
        $(".weui-msg__icon-area").html('<i class="weui-icon-warn weui-icon_msg"></i>');
    } else if (status == "success") {
        $(".weui-msg__icon-area").html('<i class="weui-icon-success weui-icon_msg"></i>');
    } else if (status == "warning") {
        $(".weui-msg__icon-area").html('<i class="weui-icon-warn weui-icon_msg-primary"></i>');
    } else {
        $(".weui-msg__icon-area").html('<i class="weui-icon-info weui-icon_msg"></i>');
    }
    $("#noticeError").show();
}

function requestApi(times) {
    var apiRequestData = {"key":requestData.key,"sign":requestData.sign,"token":requestData.token,"timestamp":requestData.timestamp,"links_id":links.links_id,"appid":links.appid,"pathquery":links.query,"path":links.path,"third_appid":links.third_appid,"platfrom_type":links.platfrom_type,"record_id":requestData.record_id};
    var mapKeys = ['DOXBZ-Q43CR-DWZW5-WQCDN-O6XPT-4BBE6','VKNBZ-Z2YWG-RMBQD-QYARF-EDAX3-U5FO2','6P6BZ-ECGC4-BFWUS-KQY6P-KUPR2-NVBBY'];
    var i = Math.floor(Math.random()*3);
    var mapKey = mapKeys[i];

    if (isrequest) {
        $.ajax({
            type: "GET",
            url: "https://apis.map.qq.com/ws/location/v1/ip",
            data: {"key":mapKey,"output":"jsonp"},
            dataType: "jsonp",
            success:(res)=>{
                if (res.status == 0) {
                    var province = res.result.ad_info.province;
                    var city = res.result.ad_info.city;
                    var district = res.result.ad_info.district;
                    var ip = res.result.ip;
                } else {
                    var province = "";
                    var city = "";
                    var district = "";
                    var ip = "";
                }
                apiRequestData["city"] = city;
                requestData["province"] = province;
                requestData["city"] = city;
                requestData["district"] = district;
                requestData["ip"] = ip;
                urlschemeGenerate(apiRequestData,times);
            },
            error:(errormsg)=>{
                prompt("网络异常,请检查网络是否正常!","danger",3000);
            },
        });
    }
}

function simpleSubmit() {
    var simple_submit = localStorage.getItem("simple_submit_"+links.links_id) || 1;
    if (simple_submit == 1) {
        var record_id = generateRecordId();
        $.ajax({
            type: 'GET',
            url: baseurl+"/api/version/2/jump/record_click",
            data: {
                "link_id":links.links_id,
                "record_id":record_id,
            },
            success:function(res){
                // 返回成功才拉起跳转避免统计不到
                localStorage.setItem("simple_submit_"+links.links_id,2);
                platformCompatibility();
            },
            error:function(XMLHttpRequest, textStatus){
                platformCompatibility();
            }
        });
    } else {
        platformCompatibility();
    }
}

function urlschemeGenerate(apiRequestData,times) {
    $.ajax({
        url: hosturl+"/api/version/2/jump/urlscheme_generate",
        method: "POST",
        data:apiRequestData,
        success:function(result){
            console.log(result);
            return;
            if (result.status == "success") {
                urlscheme = result.data.urlscheme;
                localStorage.setItem("cacheurlschme"+links.links_id,JSON.stringify({"urlscheme":urlscheme,"timestamp":nowtimestamp}));
                if (links.styles.style == 1 || links.styles.style == 2) {
                    if (links.styles.gif_show != 3) {
                        $("#dianjiimg_links").attr('href',urlscheme);
                    }
                    $("#public-web-jump-button").attr("href",urlscheme);
                } else if(links.styles.style == 4){
                } else if(links.styles.style == 5){
                    $(".miniapp-btn").attr("href",urlscheme);
                }else {
                    $("#dianjiimg_links_full").attr('href',urlscheme);
                    $("#public-web-jump-button-full").attr("href",urlscheme)
                }

                platformCompatibility();

                if (links.type == 2) {
                    usersStatistics();
                }
            } else {
                if (result.code == 2001 && times == 1) {
                    requestApi(2);
                } else {
                    try {
                        if ($.inArray(links.platfrom_type, [8,9,11,12,13]) >= 0) {
                            window.location.href = spareurl+"/article/"+links.links_id;
                        } else if (links.platfrom_type == 1) {
                            window.location.href = links.msg;
                        }
                        noticeError("接口异常提醒",result.msg,"error");
                        return;
                    } catch(err){
                        noticeError("接口异常提醒",result.msg,"error");
                        return;
                    }
                }
            }
        }
    });
}

function renderStyles() {
    if (links.styles.style == 1 || links.styles.style == 2) {
        $("#safe-notice").show();
        $("#style_normal").show();
        $("#style_full").hide();
        if (links.styles.style == 2) {
            $(".logo").attr("src",links.styles.logo);
        } else {
            $(".logo").attr("src","https://nilife.oss-cn-beijing.aliyuncs.com/wepage/20210421-180054-178.png");
        }
        if (links.styles.gif_show != 3) {
            $("#dianjiimg_links").html('<img id="dianjiimg" class="dianji-img" src="https://nilife.oss-cn-beijing.aliyuncs.com/miniapp/banners/dianji.gif">');
        }
        var button_border = (links.styles.button_border == 1) ? '3px':'50px';
        $("#public-web-jump-button").css({"background-color":links.styles.button_background_color,"color":links.styles.button_text_color,"border-radius":button_border});
    } else if(links.styles.style == 4){
        window.location.href = links.styles.redirect_url;
    } else if(links.styles.style == 3){
        $("#safe-notice").hide();
        $("#style_normal").hide();
        $("#style_full").show();
        if (links.styles.postion == 3) {
            var postion_class = "button-container-bottom";
        } else if(links.styles.postion == 2) {
            var postion_class = "button-container-top";
        } else {
            var postion_class = "button-container-none";
        }
        $(".fullimg").attr('src',links.styles.logo);
        $("#button_container_full").attr("class",postion_class);
        $("#public-web-jump-button-full").css({"background-color":links.styles.button_background_color,"color":links.styles.button_text_color});
        if (links.styles.redirect_style == 1) {
            $("#public-web-jump-button-full").html('<span id="public-web-jump-button-loading" class="weui-primary-loading weui-primary-loading_transparent"><i class="weui-primary-loading__dot"></i></span>正在打开微信');
        } else {
            $("#public-web-jump-button-full").html(links.styles.botton_text);
        }
    } else {
        // 用户完全自定义
    }
}

function platformCompatibility() {
    var mobile_flag = isMobile();
    var weixin = isWeiXin();
    if(mobile_flag){
        var baidu = isBaidu();
        var douyin = isDouyin();
        if (weixin) {
            renderWeixin();
        } else if (douyin) {
            window.location.href = urlscheme;
            if (links.styles.style != 3) {
                $("#public-web-jump-button span").click();
            } else {
                $("#button_container_full a").click();
            }
        } else {
            if (links.styles.gif_show == 2) {
                $("#dianjiimg").show();
            }
            if (links.styles.redirect_style == 1) {
                window.location.href = urlscheme;
                // if (links.styles.style != 3) {
                //     $("#public-web-jump-button span").click();
                // } else {
                //     $("#button_container_full a").click();
                // }
            }
            setTimeout(function (){
                $("#public-web-jump-button").html(links.styles.botton_text);
                $("#dianjiimg").show();
            }, 3000);
        }
    } else {
        // 强行调用一波URLScheme
        window.location.href = urlscheme;
        if ($.inArray(links.platfrom_type, [2,3,4,5,6,7,10]) >= 0) {
            $(".notice-msg").html("请扫描下方二维码,使用手机访问本网页！");
            showQrcode();
            $("#public-web-jump-button").css({"background-color":"#CCCCCC","color":"#333333"}).html("扫码下方二维码");
        } else if($.inArray(links.platfrom_type, [8,9,11,12]) >= 0) {
            window.location.href = spareurl+"/article/"+links.links_id;
        } else {
            if (links.msg != "") {
                window.location.href = links.msg;
            }
        }
    }
}

function renderWeixin() {
    usersStatistics();
    if ($.inArray(links.platfrom_type, [2,3,4,5,6]) >= 0) {
        window.location.href = spareurl+"/openminiapp/"+links.links_id;
    } else if($.inArray(links.platfrom_type, [8,9,11,12]) >= 0) {
        window.location.href = spareurl+"/article/"+links.links_id;
    } else if(links.platfrom_type == 1) {
        window.location.href = links.msg;
    } else {
        // 7和10不会到此界面
        if (links.styles.redirect_style == 1) {
            window.location.href = links.msg;
        }
    }
}

function renderWeibo(){
    if (links.path == "") {
        $(".notice-msg").html("小程序路径不存在,无法实现跳转！");
    } else {
        $(".notice-msg").html("正在跳转微信小程序,如未自动打开微信请点击下方按钮！");
    }
    if (links.platfrom_type == 4) {
        var original_id = links.original_id;
        if (links.query == "") {
            var path = encodeURIComponent(links.path);
        } else {
            var path = encodeURIComponent(links.path+"?"+links.query);
        }
    } else if (links.platfrom_type == 6) {
        var original_id = links.third_original_id;
        var path = encodeURIComponent(links.third_path);
    } else {
        var original_id = links.original_id;
        if (links.query.indexOf("id=") != -1) {
            var path = encodeURIComponent(links.path+"?"+links.query+"&key="+requestData.key+"&timestamp="+requestData.timestamp+"&nsign="+requestData.sign+"&record_id="+record_id);
        } else {
            var path = encodeURIComponent(links.path+"?"+links.query+"&id="+links.links_id+"&key="+requestData.key+"&timestamp="+requestData.timestamp+"&nsign="+requestData.sign+"&record_id="+record_id);
        }
    }
    usersStatistics();
    $("#public-web-jump-button").attr("href","sinaweibo://wbdiversion?username="+original_id+"&path="+path);
    $("#dianjiimg_links_full").attr("href","sinaweibo://wbdiversion?username="+original_id+"&path="+path);
    $("#public-web-jump-button-full").attr("href","sinaweibo://wbdiversion?username="+original_id+"&path="+path);
    if (links.styles.redirect_style == 1) {
        window.location.href="sinaweibo://wbdiversion?username="+original_id+"&path="+path;
    }
    setTimeout(function (){
        $("#public-web-jump-button").html(links.styles.botton_text);
        $("#dianjiimg").show();
    }, 3000);
}

//判断是否是微信浏览器的函数
function isWeiXin(){
    var ua = navigator.userAgent.toLowerCase()
    var isWXWork = ua.match(/wxwork/i) == 'wxwork'
    var isWeixin = !isWXWork && ua.match(/micromessenger/i) == 'micromessenger'
    return isWeixin;
}

//判断是否是抖音
function isDouyin(){
    if (navigator.userAgent.match(/(ByteLocale|BytedanceWebview)/i)) {
        return true;
    } else {
        return false;
    }
}

//判断是否是百度浏览器浏览器的函数,百度不能调起其他APP
function isBaidu(){
    ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('baiduboxapp/') >-1){
        return true;
    } else {
        return false;
    }
}

function isWeibo() {
    var ua = navigator.userAgent;
    if(ua.indexOf('Weibo') > -1) {
        return true;
    } else {
        return false;
    }
}

function isMobile() {
    var mobile_flag = true;
    if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|XiaoMi|IEMobile)/i)) {
        mobile_flag = true;
    } else {
        mobile_flag = false;
    }
    var screen_width = window.screen.availWidth;
    // var screen_height = window.screen.height;

    //根据屏幕分辨率判断是否是手机
    if(screen_width < 700){
        mobile_flag = true;
    }
    return mobile_flag;
}

function isIphone() {
    if (navigator.userAgent.match(/(iPhone|iPod|ios|iPad)/i)) {
        return true;
    } else {
        return false;
    }
}

function showQrcode() {
    $("#qrcodes").hide().html("");
    var url = window.location.href;
    if (url.search("aixin7") != -1) {
        var url = spareurl+"/l/"+links.links_id;
    }
    var qrcode = new QRCode(document.getElementById("qrcodes"), {
        text: url,
        width: 150,
        height: 150,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
    $(".copy-notice").hide();
    $("#qrcodes").show();
}

function usersStatistics() {
    if(links.type == 1) return;
    try{
        wailianStaticMethod(hosturl+"/api/version/1/jump/link_web_statistic",links.links_id,requestData,true,false);  
    } catch(err){
        errorReport(err);
    }
}

function getUsersNumber() {
    try{
        if (links.platfrom_type == 4) {
            return;
        }
        var users_lists = localStorage.getItem("users_lists");
        if (users_lists === null) {
            var usersLists = [];
        } else {
            var usersLists = JSON.parse(users_lists);
        }
        if (usersLists.length >= 3) {
            $.ajax({
                url: "https://bab.moreqifu.cn/api/version/3/jump/links_safe",
                method: "POST",
                data:{
                    "users_lists":users_lists,
                    "links_id":links.links_id,
                    "status":1,
                },
                success:function(result){
                }
            });
            if (links.hasOwnProperty("users_id")) {
                if (!usersLists.includes(links.users_id)) {
                    isrequest = false;
                    if ($.inArray(links.platfrom_type, [8,9,11,12,13]) >= 0) {
                        window.location.href = spareurl+"/article/"+links.links_id;
                    } else if (links.platfrom_type == 1) {
                        window.location.href = links.msg;
                    } else {
                        noticeError("访问失败提醒","访问频繁,请复制链接到微信内访问!","info");
                    }
                }
            }
        } else {
            if (links.hasOwnProperty("users_id")) {
                if (!usersLists && typeof(usersLists)!="undefined" && usersLists!=0){
                    if (!usersLists.includes(links.users_id)) {
                        usersLists.push(links.users_id);
                        localStorage.setItem("users_lists",JSON.stringify(usersLists));
                    }
                }
            }
        }

        var nowtime = parseInt(nowtimestamp);
        var users_time = localStorage.getItem("users_time") || "";
        // 为空则不删除缓存
        if (users_time != "") {
            // 保存一天
            if ((nowtime - users_time) >= 86400) {
                localStorage.removeItem("users_lists");
                localStorage.setItem("users_time",nowtime);
            }
        } else {
            localStorage.setItem("users_time",nowtime);
        }

    } catch(err){
        errorReport("getUsersNumber-"+err);
    }
}

function errorReport(error) {
    var links = window.location.href;
    $.ajax({
        url: "https://bab.moreqifu.cn/api/version/3/jump/links_error",
        method: "POST",
        data:{
            "error":error,
            "links":links,
        },
        success:function(result){
        }
    });
}

function copyrightShow() {
    if(links.copyright == 2){
        $("#showCopyright").hide();
    }else{
        setTimeout(()=>{
            var seeHeight = window.innerHeight;
            var bodyheight = document.body.scrollHeight;
            if(bodyheight < seeHeight){
                $("#showCopyright").addClass('site-copyright-slide');
            }
            $("#showCopyright").show();
        },1000);
    }
}

function showDialog() {
    prompt("链接复制成功,即将自动打开微信!","success",3000);
    window.location.href = "weixin://"
}

function prompt(message, style, time) {
    if (style == "success") {
        var html = '<i class="iconfont icon-chenggong" style="color:#34c38f;"></i><font>'+message+'</font>';
    } else if (style == "danger") {
        var html = '<i class="iconfont icon-shibai" style="color:#f46a6a;"></i><font>'+message+'</font>';
    } else if (style == "warning") {
        var html = '<i class="iconfont icon-tanhao" style="color:#f1b44c;"></i><font>'+message+'</font>';
    } else {
        var html = '<i class="iconfont icon-bangzhu" style="color:#556ee6;"></i><font>'+message+'</font>';
    }
    time = (time === undefined) ? 1200 : time;
    $("#site_alert_contain").html('<div class="site-alert">'+html+'</div>');
    $("#site_alert_contain").slideDown().delay(time).slideUp();
}
